#encoding=utf8
from django.contrib.auth import *
from django.contrib.auth.models import *
from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage
from django.core.urlresolvers import *
from django.db import transaction
from django.db.models import Q
from django.forms import *
from django.http import *
from django.shortcuts import *
from django.views.decorators.http import require_http_methods
import json
import sets

from trp.models import *
from utils.JsonResponse import *
from utils.decorators import *
from utils.utils import *
from website.settings import LOGGER as logger

@login_required_ajax
def main(request):
    return render_to_response('trp/positionattr.html', {'user' : request.user, 'page' : 'positionattr'})

@login_required_ajax
def get_position_attrs(request):
    attrs = PositionAttr.objects.all().order_by("-id")
    attrsArr =[]
    for attr in attrs:
        attrsArr.append({"id":attr.id,"name":attr.name})
    return JsonResponse({"attrs":attrsArr})

@login_required_ajax
def do_create(request):
    param = json.loads(request.body)
    name = param.get("name")
    try :
        attr_tuple = PositionAttr.objects.get_or_create(name=name)
        if attr_tuple[1] :
            return JsonResponse({"message":"ok","id":attr_tuple[0].id})
        else :
            return JsonResponseBadrequest({"message":"name already exists"})
    except Exception,e:
        logger.exception(e)
        return JsonResponseBadrequest({"message":str(e)})
@login_required_ajax
def do_check(request):
    param = json.loads(request.body)
    position_attr_id = param.get("position_attr_id")
    try :
        attr = PositionAttr.objects.prefetch_related("position_set").get(pk = int(position_attr_id))
        flag = len(attr.position_set.all())>0
        return JsonResponse({"related":flag})
    except Exception,e:
        return JsonResponseBadrequest({"message":str(e)})

@login_required_ajax
@transaction.atomic
def do_delete(request):
    param = json.loads(request.body)
    attr_id= param.get("position_attr_id")
    try :
        with transaction.atomic():
            attr = PositionAttr.objects.get(pk=int(attr_id))
            attr.position_set.clear()
            attr.delete()
        return JsonResponse({"message":"ok"})
    except Exception,e:
        return JsonResponseBadrequest({"message":str(e)})

@login_required_ajax
def get_position_attrs_list(request):
    param = json.loads(request.body)
    searchTxt = param.get("searchTxt","")
    pageNo = param.get('pageNo',1)
    pageSize = param.get("pageSize")or 20
    orderBy = param.get("orderBy","id")
    order = param.get("order","desc")
    if orderBy :
        orderBy = (order =="asc" and "" or "-") + orderBy
    data=None
    count=0
    qset = PositionAttr.objects.all()
    if orderBy :
        qset = qset.order_by(orderBy)
    
    paginator = Paginator(qset, pageSize)
    try:
        data = paginator.page(pageNo)
        count=paginator.count
    except PageNotAnInteger:
        data = paginator.page(1)
    except EmptyPage:
        data = paginator.page(paginator.num_pages)
    dataArr=[]
    for attr in data.object_list :
        tmp ={}
        tmp["id"]=attr.id
        tmp["name"]=attr.name
        dataArr.append(tmp)
    result={}
    result["bodyData"]=dataArr
    result["pageSize"]=pageSize
    result["pageNo"]=pageNo
    result["totalCount"]=count
    return JsonResponse(result)